package ro.peoplecentric.ctc.common.spring;

import java.util.Map;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * This class is used to create VIEW scope in spring. It works like JSF
 *
 * @ViewScope annotation. New object is created on demand when it is not present in the JSF ViewMap. Objects are
 * collected by java GC
 * 
 * @author pguzun
 */
public class ViewScope implements Scope {

    @Override
    /**
     * Get the model by name. If object exists in current ViewRoot return existing one. If object is missing create new
     * object and put in the ViewRoot.
     */
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();

        if (viewMap.containsKey(name)) {
            return viewMap.get(name);
        } else {
            Object object = objectFactory.getObject();
            viewMap.put(name, object);
            return object;
        }
    }

    @Override
    public Object remove(String name) {
        return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
